5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup Maintenance ExternalStorage
24 use MediaWiki\MediaWikiServices
;
26 if ( !defined( 'MEDIAWIKI' ) ) {
27 $optionsWithoutArgs = [ 'fix' ];
28 require_once __DIR__
. '/../commandLine.inc';
30 $cs = new CheckStorage
;
31 $fix = isset( $options['fix'] );
32 $xml = $args[0] ??
false;
33 $cs->check( $fix, $xml );
36 // ----------------------------------------------------------------------------------
39 * Maintenance script to do various checks on external storage.
41 * @fixme this should extend the base Maintenance class
42 * @ingroup Maintenance ExternalStorage
45 const CONCAT_HEADER
= 'O:27:"concatenatedgziphistoryblob"';
46 public $oldIdMap, $errors;
47 public $dbStore = null;
49 public $errorDescriptions = [
50 'restore text' => 'Damaged text, need to be restored from a backup',
51 'restore revision' => 'Damaged revision row, need to be restored from a backup',
52 'unfixable' => 'Unexpected errors with no automated fixing method',
53 'fixed' => 'Errors already fixed',
54 'fixable' => 'Errors which would already be fixed if --fix was specified',
57 function check( $fix = false, $xml = '' ) {
58 $dbr = wfGetDB( DB_REPLICA
);
60 print "Checking, will fix errors if possible...\n";
62 print "Checking...\n";
64 $maxRevId = $dbr->selectField( 'revision', 'MAX(rev_id)', '', __METHOD__
);
68 $knownFlags = [ 'external', 'gzip', 'object', 'utf-8' ];
71 'restore revision' => [],
77 for ( $chunkStart = 1; $chunkStart < $maxRevId; $chunkStart +
= $chunkSize ) {
78 $chunkEnd = $chunkStart +
$chunkSize - 1;
79 // print "$chunkStart of $maxRevId\n";
81 // Fetch revision rows
84 $res = $dbr->select( 'revision', [ 'rev_id', 'rev_text_id' ],
85 [ "rev_id BETWEEN $chunkStart AND $chunkEnd" ], __METHOD__
);
86 foreach ( $res as $row ) {
87 $this->oldIdMap
[$row->rev_id
] = $row->rev_text_id
;
89 $dbr->freeResult( $res );
91 if ( !count( $this->oldIdMap
) ) {
96 $missingTextRows = array_flip( $this->oldIdMap
);
101 [ 'old_id', 'old_flags' ],
102 [ 'old_id' => $this->oldIdMap
],
105 foreach ( $res as $row ) {
109 $flags = $row->old_flags
;
112 // Create flagStats row if it doesn't exist
113 $flagStats = $flagStats +
[ $flags => 0 ];
115 $flagStats[$flags]++
;
118 unset( $missingTextRows[$row->old_id
] );
120 // Check for external or object
121 if ( $flags == '' ) {
124 $flagArray = explode( ',', $flags );
126 if ( in_array( 'external', $flagArray ) ) {
127 $externalRevs[] = $id;
128 } elseif ( in_array( 'object', $flagArray ) ) {
132 // Check for unrecognised flags
133 if ( $flags == '0' ) {
134 // This is a known bug from 2004
135 // It's safe to just erase the old_flags field
137 $this->addError( 'fixed', "Warning: old_flags set to 0", $id );
138 $dbw = wfGetDB( DB_MASTER
);
140 $dbw->update( 'text', [ 'old_flags' => '' ],
141 [ 'old_id' => $id ], __METHOD__
);
144 $this->addError( 'fixable', "Warning: old_flags set to 0", $id );
146 } elseif ( count( array_diff( $flagArray, $knownFlags ) ) ) {
147 $this->addError( 'unfixable', "Error: invalid flags field \"$flags\"", $id );
150 $dbr->freeResult( $res );
152 // Output errors for any missing text rows
153 foreach ( $missingTextRows as $oldId => $revId ) {
154 $this->addError( 'restore revision', "Error: missing text row", $oldId );
157 // Verify external revisions
158 $externalConcatBlobs = [];
159 $externalNormalBlobs = [];
160 if ( count( $externalRevs ) ) {
163 [ 'old_id', 'old_flags', 'old_text' ],
164 [ 'old_id' => $externalRevs ],
167 foreach ( $res as $row ) {
168 $urlParts = explode( '://', $row->old_text
, 2 );
169 if ( count( $urlParts ) !== 2 ||
$urlParts[1] == '' ) {
170 $this->addError( 'restore text', "Error: invalid URL \"{$row->old_text}\"", $row->old_id
);
173 list( $proto, ) = $urlParts;
174 if ( $proto != 'DB' ) {
177 "Error: invalid external protocol \"$proto\"",
181 $path = explode( '/', $row->old_text
);
184 if ( isset( $path[4] ) ) {
185 $externalConcatBlobs[$cluster][$id][] = $row->old_id
;
187 $externalNormalBlobs[$cluster][$id][] = $row->old_id
;
190 $dbr->freeResult( $res );
193 // Check external concat blobs for the right header
194 $this->checkExternalConcatBlobs( $externalConcatBlobs );
196 // Check external normal blobs for existence
197 if ( count( $externalNormalBlobs ) ) {
198 if ( is_null( $this->dbStore
) ) {
199 $this->dbStore
= new ExternalStoreDB
;
201 foreach ( $externalConcatBlobs as $cluster => $xBlobIds ) {
202 $blobIds = array_keys( $xBlobIds );
203 $extDb =& $this->dbStore
->getSlave( $cluster );
204 $blobsTable = $this->dbStore
->getTable( $extDb );
205 $res = $extDb->select( $blobsTable,
207 [ 'blob_id' => $blobIds ],
210 foreach ( $res as $row ) {
211 unset( $xBlobIds[$row->blob_id
] );
213 $extDb->freeResult( $res );
214 // Print errors for missing blobs rows
215 foreach ( $xBlobIds as $blobId => $oldId ) {
218 "Error: missing target $blobId for one-part ES URL",
224 // Check local objects
228 if ( count( $objectRevs ) ) {
232 [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ],
233 [ 'old_id' => $objectRevs ],
236 foreach ( $res as $row ) {
237 $oldId = $row->old_id
;
239 if ( !preg_match( '/^O:(\d+):"(\w+)"/', $row->header
, $matches ) ) {
240 $this->addError( 'restore text', "Error: invalid object header", $oldId );
244 $className = strtolower( $matches[2] );
245 if ( strlen( $className ) != $matches[1] ) {
248 "Error: invalid object header, wrong class name length",
254 $objectStats = $objectStats +
[ $className => 0 ];
255 $objectStats[$className]++
;
257 switch ( $className ) {
258 case 'concatenatedgziphistoryblob':
261 case 'historyblobstub':
262 case 'historyblobcurstub':
263 if ( strlen( $row->header
) == $headerLength ) {
264 $this->addError( 'unfixable', "Error: overlong stub header", $oldId );
267 $stubObj = unserialize( $row->header
);
268 if ( !is_object( $stubObj ) ) {
269 $this->addError( 'restore text', "Error: unable to unserialize stub object", $oldId );
272 if ( $className == 'historyblobstub' ) {
273 $concatBlobs[$stubObj->mOldId
][] = $oldId;
275 $curIds[$stubObj->mCurId
][] = $oldId;
279 $this->addError( 'unfixable', "Error: unrecognised object class \"$className\"", $oldId );
282 $dbr->freeResult( $res );
285 // Check local concat blob validity
286 $externalConcatBlobs = [];
287 if ( count( $concatBlobs ) ) {
291 [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ],
292 [ 'old_id' => array_keys( $concatBlobs ) ],
295 foreach ( $res as $row ) {
296 $flags = explode( ',', $row->old_flags
);
297 if ( in_array( 'external', $flags ) ) {
298 // Concat blob is in external storage?
299 if ( in_array( 'object', $flags ) ) {
300 $urlParts = explode( '/', $row->header
);
301 if ( $urlParts[0] != 'DB:' ) {
304 "Error: unrecognised external storage type \"{$urlParts[0]}",
308 $cluster = $urlParts[2];
310 if ( !isset( $externalConcatBlobs[$cluster][$id] ) ) {
311 $externalConcatBlobs[$cluster][$id] = [];
313 $externalConcatBlobs[$cluster][$id] = array_merge(
314 $externalConcatBlobs[$cluster][$id], $concatBlobs[$row->old_id
]
320 "Error: invalid flags \"{$row->old_flags}\" on concat bulk row {$row->old_id}",
321 $concatBlobs[$row->old_id
] );
323 } elseif ( strcasecmp(
324 substr( $row->header
, 0, strlen( self
::CONCAT_HEADER
) ),
329 "Error: Incorrect object header for concat bulk row {$row->old_id}",
330 $concatBlobs[$row->old_id
]
334 unset( $concatBlobs[$row->old_id
] );
336 $dbr->freeResult( $res );
339 // Check targets of unresolved stubs
340 $this->checkExternalConcatBlobs( $externalConcatBlobs );
344 print "\n\nErrors:\n";
345 foreach ( $this->errors
as $name => $errors ) {
346 if ( count( $errors ) ) {
347 $description = $this->errorDescriptions
[$name];
348 echo "$description: " . implode( ',', array_keys( $errors ) ) . "\n";
352 if ( count( $this->errors
['restore text'] ) && $fix ) {
353 if ( (string)$xml !== '' ) {
354 $this->restoreText( array_keys( $this->errors
['restore text'] ), $xml );
356 echo "Can't fix text, no XML backup specified\n";
360 print "\nFlag statistics:\n";
361 $total = array_sum( $flagStats );
362 foreach ( $flagStats as $flag => $count ) {
363 printf( "%-30s %10d %5.2f%%\n", $flag, $count, $count / $total * 100 );
365 print "\nLocal object statistics:\n";
366 $total = array_sum( $objectStats );
367 foreach ( $objectStats as $className => $count ) {
368 printf( "%-30s %10d %5.2f%%\n", $className, $count, $count / $total * 100 );
372 function addError( $type, $msg, $ids ) {
373 if ( is_array( $ids ) && count( $ids ) == 1 ) {
374 $ids = reset( $ids );
376 if ( is_array( $ids ) ) {
378 foreach ( $ids as $id ) {
379 $revIds = array_merge( $revIds, array_keys( $this->oldIdMap
, $id ) );
381 print "$msg in text rows " . implode( ', ', $ids ) .
382 ", revisions " . implode( ', ', $revIds ) . "\n";
385 $revIds = array_keys( $this->oldIdMap
, $id );
386 if ( count( $revIds ) == 1 ) {
387 print "$msg in old_id $id, rev_id {$revIds[0]}\n";
389 print "$msg in old_id $id, revisions " . implode( ', ', $revIds ) . "\n";
392 $this->errors
[$type] = $this->errors
[$type] +
array_flip( $revIds );
395 function checkExternalConcatBlobs( $externalConcatBlobs ) {
396 if ( !count( $externalConcatBlobs ) ) {
400 if ( is_null( $this->dbStore
) ) {
401 $this->dbStore
= new ExternalStoreDB
;
404 foreach ( $externalConcatBlobs as $cluster => $oldIds ) {
405 $blobIds = array_keys( $oldIds );
406 $extDb =& $this->dbStore
->getSlave( $cluster );
407 $blobsTable = $this->dbStore
->getTable( $extDb );
408 $headerLength = strlen( self
::CONCAT_HEADER
);
409 $res = $extDb->select( $blobsTable,
410 [ 'blob_id', "LEFT(blob_text, $headerLength) AS header" ],
411 [ 'blob_id' => $blobIds ],
414 foreach ( $res as $row ) {
415 if ( strcasecmp( $row->header
, self
::CONCAT_HEADER
) ) {
418 "Error: invalid header on target $cluster/{$row->blob_id} of two-part ES URL",
419 $oldIds[$row->blob_id
]
422 unset( $oldIds[$row->blob_id
] );
424 $extDb->freeResult( $res );
426 // Print errors for missing blobs rows
427 foreach ( $oldIds as $blobId => $oldIds2 ) {
430 "Error: missing target $cluster/$blobId for two-part ES URL",
437 function restoreText( $revIds, $xml ) {
439 $tmpDir = wfTempDir();
441 if ( !count( $revIds ) ) {
445 print "Restoring text from XML backup...\n";
447 $revFileName = "$tmpDir/broken-revlist-$wgDBname";
448 $filteredXmlFileName = "$tmpDir/filtered-$wgDBname.xml";
450 // Write revision list
451 if ( !file_put_contents( $revFileName, implode( "\n", $revIds ) ) ) {
452 echo "Error writing revision list, can't restore text\n";
458 echo "Filtering XML dump...\n";
460 passthru( 'mwdumper ' .
462 "--output=file:$filteredXmlFileName",
463 "--filter=revlist:$revFileName",
469 echo "mwdumper died with exit status $exitStatus\n";
474 $file = fopen( $filteredXmlFileName, 'r' );
476 echo "Unable to open filtered XML file\n";
481 $dbr = wfGetDB( DB_REPLICA
);
482 $dbw = wfGetDB( DB_MASTER
);
486 $source = new ImportStreamSource( $file );
487 $importer = new WikiImporter(
489 MediaWikiServices
::getInstance()->getMainConfig()
491 $importer->setRevisionCallback( [ $this, 'importRevision' ] );
492 $importer->setNoticeCallback( function ( $msg, $params ) {
493 echo wfMessage( $msg, $params )->text() . "\n";
495 $importer->doImport();
498 function importRevision( &$revision, &$importer ) {
499 $id = $revision->getID();
500 $content = $revision->getContent( Revision
::RAW
);
503 if ( $content === null ) {
504 echo "Revision $id is broken, we have no content available\n";
509 $text = $content->serialize();
510 if ( $text === '' ) {
511 // This is what happens if the revision was broken at the time the
512 // dump was made. Unfortunately, it also happens if the revision was
513 // legitimately blank, so there's no way to tell the difference. To
514 // be safe, we'll skip it and leave it broken
516 echo "Revision $id is blank in the dump, may have been broken before export\n";
522 // No ID, can't import
523 echo "No id tag in revision, can't import\n";
528 // Find text row again
529 $dbr = wfGetDB( DB_REPLICA
);
530 $oldId = $dbr->selectField( 'revision', 'rev_text_id', [ 'rev_id' => $id ], __METHOD__
);
532 echo "Missing revision row for rev_id $id\n";
538 $flags = Revision
::compressRevisionText( $text );
540 // Update the text row
541 $dbw = wfGetDB( DB_MASTER
);
542 $dbw->update( 'text',
543 [ 'old_flags' => $flags, 'old_text' => $text ],
544 [ 'old_id' => $oldId ],
545 __METHOD__
, [ 'LIMIT' => 1 ]
548 // Remove it from the unfixed list and add it to the fixed list
549 unset( $this->errors
['restore text'][$id] );
550 $this->errors
['fixed'][$id] = true;